package cn.tedu.cat.controller;

import cn.tedu.cat.entity.User;
import cn.tedu.cat.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg(User user){
        //查询用户名是否存在
        User u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            return 2;//用户名已存在
        }
        mapper.insert(user);
        return 1;//注册成功
    }

    @RequestMapping("/login")
    public int login(User user, HttpSession session){
        User u = mapper.selectByUsername(user.getUsername());
        if (u!=null){
            if (u.getPassword().equals(user.getPassword())){
                //把当前登录成功的用户对象保存到Session会话对象中
                session.setAttribute("u",u);
                return 1;//登录成功
            }
            return 3;//密码错误
        }
        return 2;//用户名不存在
    }

    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session){
        //从当前的会话对象中获取曾经登录成功时的用户对象
        return (User) session.getAttribute("u");
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //删除会话对象里面的user对象
        session.removeAttribute("u");
    }
}
